<template>
  <div class="config-list">
    <div class="page-header">
      <div class="header-left">
        <h3>全局配置管理</h3>
        <p>管理系统的全局默认配置</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新建配置
        </el-button>
      </div>
    </div>

    <div class="filter-bar">
      <el-form :model="queryForm" inline>
        <el-form-item label="配置名称">
          <el-input
            v-model="queryForm.name"
            placeholder="请输入配置名称"
            clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 配置表格 -->
    <el-table
      v-loading="loading"
      :data="configs"
      stripe
      class="config-table">

      <el-table-column prop="name" label="配置名称" min-width="150">
        <template #default="{ row }">
          <div class="config-name">
            <span>{{ row.name }}</span>
            <el-tag v-if="row.isActive === 1" type="success" size="small">激活</el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="filePath" label="文件路径" min-width="200" show-overflow-tooltip />

      <el-table-column prop="updatedAt" label="更新时间" width="160">
        <template #default="{ row }">
          {{ formatDateTime(row.updatedAt) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            v-if="row.isActive !== 1"
            type="success"
            size="small"
            @click="handleActivate(row)">
            激活
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { http } from '@/utils/request'
import { ElMessageBox, ElMessage } from 'element-plus'

const router = useRouter()

// 状态
const loading = ref(false)
const configs = ref([])

// 查询表单
const queryForm = reactive({
  name: ''
})

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 初始化
onMounted(() => {
  loadConfigs()
})

// 加载配置列表
const loadConfigs = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      name: queryForm.name || undefined
    }

    const response = await http.get('/configs', params)
    const { list, total } = response.data

    configs.value = list
    pagination.total = total
  } catch (error) {
    ElMessage.error('加载配置列表失败')
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  pagination.page = 1
  loadConfigs()
}

const handleReset = () => {
  queryForm.name = ''
  handleQuery()
}

// 分页变化
const handlePageChange = (page) => {
  pagination.page = page
  loadConfigs()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadConfigs()
}

// 新建配置
const handleCreate = () => {
  router.push('/configs/edit')
}

// 编辑配置
const handleEdit = (row) => {
  router.push(`/configs/edit/${row.id}`)
}

// 激活配置
const handleActivate = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要激活配置 "${row.name}" 吗？这将停用其他全局配置。`,
      '确认激活',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await http.post(`/configs/${row.id}/activate`)
    ElMessage.success('配置已激活')
    loadConfigs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('激活配置失败')
    }
  }
}

// 删除配置
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除配置 "${row.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await http.delete(`/configs/${row.id}`)
    ElMessage.success('删除成功')
    loadConfigs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 格式化时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}
</script>

<style lang="scss" scoped>
.config-list {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .header-left {
      h3 {
        margin: 0 0 5px;
        color: #303133;
        font-size: 18px;
        font-weight: 600;
      }

      p {
        margin: 0;
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .filter-bar {
    margin-bottom: 20px;
    padding: 15px 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .config-table {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .config-name {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style>
